<template>
  <view>
    <u-toast ref="uToast" />
    <canvas
      canvas-id="mycanvas"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
      :disable-scroll="true"
      class="canvas"
      id="canvas"
      :style="{ width: width + 'rpx', height: height + 'rpx' }"
    />
    <u-row style="margin-top: 28rpx">
      <u-button plain @click="clearCanvas()">重新签名</u-button>
      <u-button type="primary" plain @click="show = true">确认提交</u-button>
    </u-row>
    <u-modal
      v-model="show"
      show-cancel-button
      content="确认提交后无法修改签名"
      confirm-text="确认"
      @confirm="saveCanvas"
    >
    </u-modal>
  </view>
</template>

<script>
import { uploadBaseUrl, baseURL } from "@/config.js";
export default {
  name: "signature",
  props: {
    width: {
      type: Number,
      default: 720,
    },
    height: {
      type: Number,
      default: 320,
    },
    image: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      ctx: null,
      points: [],
      uploadUrl: uploadBaseUrl + "/minio/uploadDeliverFile",
      uploadHeader: {
        Authorization: "Bearer " + uni.getStorageSync("token"),
      },
      uploadData: {},
      show: false,
      ok: false,
    };
  },
  methods: {
    touchStart(e) {
      if (!this.ok) {
        this.ok = true;
      }
      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = {
        X: startX,
        Y: startY,
      };
      this.points.push(startPoint);
      this.ctx.beginPath();
    },
    touchMove(e) {
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {
        X: moveX,
        Y: moveY,
      };
      this.points.push(movePoint);
      if (this.points.length >= 2) {
        this.draw();
      }
    },
    touchEnd() {
      this.points = [];
    },
    draw() {
      let point_1 = this.points[0];
      let point_2 = this.points[1];
      this.points.shift();
      this.ctx.moveTo(point_1.X, point_1.Y);
      this.ctx.lineTo(point_2.X, point_2.Y);
      this.ctx.stroke();
      this.ctx.draw(true);
    },
    clearCanvas() {
      this.ok = false;
      let width = 0;
      let height = 0;
      let query = uni.createSelectorQuery().in(this);
      query
        .select("#canvas")
        .boundingClientRect((data) => {
          this.ctx.setFillStyle("#FFFFFF");
          this.ctx.fillRect(0, 0, this.width, this.height);
          this.ctx.lineWidth = 4;
          this.ctx.lineCap = "round";
          this.ctx.lineJoin = "round";
          this.ctx.draw(true);
        })
        .exec();
    },
    saveCanvas() {
      const _self = this;
      if (!this.ok) {
        this.$refs.uToast.show({
          title: "请签字",
          type: "error",
        });
        return;
      }
      uni.canvasToTempFilePath({
        canvasId: "mycanvas",
        success({ errMsg, tempFilePath }) {
          if (errMsg === "canvasToTempFilePath:ok") {
            // _self.$emit('success', tempFilePath)
            uni.uploadFile({
              url: _self.uploadUrl,
              filePath: tempFilePath,
              name: "file",
              formData: _self.uploadData,
              header: _self.uploadHeader,
              success: (res) => {
                let resData = JSON.parse(res.data);
                if (res.statusCode === 200) {
                  _self.$emit("success", resData.data.filePath);
                } else {
                  _self.$refs.uToast.show({
                    title: "上传出错,请联系管理员",
                    type: "error",
                  });
                }
              },
              fail: (err) => {},
            });
          } else {
            _self.$emit("error", "保存失败");
          }
        },
      });
    },
  },
  created() {
    //创建绘图对象
    this.ctx = uni.createCanvasContext("mycanvas", this);
    //设置画笔样式
    this.ctx.lineWidth = 4;
    this.ctx.lineCap = "round";
    this.ctx.lineJoin = "round";
    uni.request({
      url: baseURL + "/deliver/statement/signature",
      header: {
        Authorization: "Bearer " + uni.getStorageSync("token"),
      },
      success: ({ data }) => {
        if (data.message && data.message !== "") {
          uni.downloadFile({
            url: uni.$zx.deliverDownloadBaseUrl + data.message,
            success: (res) => {
              this.ctx.drawImage(
                res.tempFilePath,
                0,
                0,
                this.width / 2,
                this.height / 2
              );
              this.ctx.draw();
              this.ok = true;
            },
            fail: (err) => {},
          });
        }
      },
    });
  },
};
</script>

<style scoped>
.canvas {
  width: 100vw;
  height: 80vh;
  margin: auto;
  background-color: #ffffff;
  border: 1px solid #ea5646;
  /* $zx-theme-color: #EA5646; */
}
</style>
